﻿
using Alison.Tools.HttpContact.Response;
using log4net.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Alison.EFCore;
using Alison.EFCore.Entity;
using Alison.EFCore.Dto;

namespace Alison.Service
{
    public class UserService : IUserService
    {
        private readonly ILogger<UserService> _logger;
        public UserService(ILogger<UserService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取用户名和密码是否正确
        /// </summary>
        /// <param name="loginDTO"></param>
        /// <returns></returns>
        public ApiResponse Login(LoginDTO loginDTO)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = db.Users.FirstOrDefault(x => x.Account.Equals(loginDTO.Username));
                if (model == null)
                    return new ApiResponse(201, "用户名不正确");
                if (model.Password.Equals(loginDTO.Password))
                    return new ApiResponse(200, "登录成功");
                return new ApiResponse(201, "密码不正确");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> Add(UserDto dto)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Users.AddAsync(new User()
                {
                    Account = dto.Account,
                    Address = dto.Address,
                    Createtime = DateTime.Now,
                    Email = dto.Email,
                    Flagadmin = dto.FlagAdmin,
                    Flagonline = dto.FlagOnline,
                    Islocked = dto.IsLocked,
                    Password = "123",
                    Tel = dto.Tel,
                    Username = dto.UserName
                });

                var ok = db.SaveChangesAsync();
                return new ApiResponse(200, ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        public async Task<ApiResponse> Delete(int id)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Users.FirstOrDefaultAsync(x => x.Id.Equals(id));
                if (model == null)
                    return new ApiResponse(201, "未找到对应数据");

                db.Entry(model).State = EntityState.Deleted;
                var ok = db.SaveChangesAsync();
                return new ApiResponse(200, ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }

        /// <summary>
        /// 查询用户(根据ID)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> Get(int id)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Users.FirstOrDefaultAsync(predicate: x => x.Id == id);
                return new ApiResponse(200, model);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);  
            }
        }

        public async Task<ApiResponse> GetAll(UserDto dto)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Users.Where(t => t.Username.Contains(dto.UserName) ||
                string.IsNullOrWhiteSpace(dto.UserName)).ToListAsync();
                      
                return new ApiResponse(200, model.OrderBy(t=>t.Id).ToList());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }


        public async Task<ApiResponse> Save(UserDto dto)
        {
            try
            {
                using var db = new AlisonDbContext();
                var model = await db.Users.FirstOrDefaultAsync(t => t.Id.Equals(dto.Id));
                 
                model.Account = dto.Account;
                model.Address = dto.Address;
                model.Email = dto.Email;
                model.Flagadmin = dto.FlagAdmin;
                model.Flagonline = dto.FlagOnline;
                model.Islocked = dto.IsLocked;
                model.Tel = dto.Tel;
                model.Username = dto.UserName;


                db.Entry(model).State = EntityState.Modified;
                var ok = db.SaveChangesAsync();
                return new ApiResponse(200, ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "");
                return new ApiResponse(500, ex.Message);
            }
        }
    }
}
